package mqttclient

import (
	"go-zero-admin/apps/modules/iot/cmd/link/gateway"
	gatewayConstant "go-zero-admin/apps/modules/iot/cmd/link/gateway/constant"
	"go-zero-admin/apps/modules/iot/cmd/link/network"
	networkConstant "go-zero-admin/apps/modules/iot/cmd/link/network/constant"
	"go-zero-admin/apps/modules/iot/cmd/link/network/mqttclient"
)

var _ iMqttClientDeviceGatewayProvider = (*mqttClientDeviceGatewayProvider)(nil)

var (
	IMqttClientDeviceGatewayProvider = new(mqttClientDeviceGatewayProvider)
)

type (
	iMqttClientDeviceGatewayProvider interface {
		gateway.IDeviceGatewayProvider
	}
	mqttClientDeviceGatewayProvider struct {
	}
)

func (m *mqttClientDeviceGatewayProvider) GetId() string {
	return "mqtt-client-gateway"
}

func (m *mqttClientDeviceGatewayProvider) GetName() string {
	return "MQTT Broker接入"
}

func (m *mqttClientDeviceGatewayProvider) GetDescription() string {
	return ""
}

func (m *mqttClientDeviceGatewayProvider) GetChannel() string {
	return "network"
}

func (m *mqttClientDeviceGatewayProvider) GetOrder() int64 {
	return 0
}

func (m *mqttClientDeviceGatewayProvider) GetTransport() gateway.ITransport {
	return new(gateway.Transport).Of(gatewayConstant.Mqtt)
}

func (m *mqttClientDeviceGatewayProvider) CreateDeviceGateway(properties *gateway.DeviceGatewayProperties) (gateway.IDeviceGateway, error) {
	// 获取网络组件
	iNetwork, err := network.INetworkManager.GetNetwork(m.GetNetworkType(), properties.NetworkConfig,
		properties.ChannelId)
	if err != nil {
		return nil, err
	}
	mqttClient := iNetwork.GetTarget().(*mqttclient.MqttClient)

	// 创建设备网关
	return &MqttClientDeviceGateway{
		Id:         properties.Id,
		MqttClient: mqttClient,
		//Topics:     strings.Split(properties.Configuration["topics"].(string), ","),
		//Qos:        properties.Configuration["qos"].(int32),
		ProtocolId: properties.Configuration["protocolId"].(int64),
		Protocol:   properties.Configuration["protocol"].(string),
	}, nil
}

func (m *mqttClientDeviceGatewayProvider) ReloadDeviceGateway(deviceGateway gateway.IDeviceGateway,
	properties *gateway.DeviceGatewayProperties) {
}

func (m *mqttClientDeviceGatewayProvider) GetNetworkType() *network.NetworkType {
	return new(network.NetworkType).Of(networkConstant.MqttClient)
}
